package resman.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import resman.bean.LoginBean;
import resman.bean.ResumeBean;
import resman.database.DatabaseHandler;
import resman.database.TransSession;
import resman.model.ActionServlet;

@SuppressWarnings("serial")
@WebServlet("/RegisterServlet")
public class RegisterServlet extends ActionServlet
{
	
	@Override
	protected void process(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException
	{
		TransSession tsession = DatabaseHandler.openSession(true);
		Session session = tsession.getSession();
		
		LoginBean login = new LoginBean();
		login.setProperties(request.getParameterMap());
		
		LoginBean result = (LoginBean) session.createQuery("from LoginBean " +
				"where email = :email")
				.setParameter("email", login.getEmail())
				.uniqueResult();
		
		String url;
		
		if (result == null)
		{			
			ResumeBean resume = new ResumeBean();
			login.setResume(resume);
			
			session.save(login);
			refreshResume(resume, session, request);
			
			clearError(request);
			url = "index.jsp";
		}
		else
		{
			setError(request,"1");
			url = "forms/register_form.jsp";
		}
		
		tsession.close();
		dispatchTo(url, request, response);
	}

}
